package net.lcheng.shop.Controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import net.lcheng.commons.utils.HttpClientUtils;
import net.lcheng.model.User;
import net.lcheng.service.UserService;
import net.lcheng.vo.WxAccessTokenModel;
import net.lcheng.vo.WxUserInfoModel;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

/**
 * Created by qiliping on 16/7/25.
 */
@Controller
public class LoginWxController {

    private static Logger log = Logger.getLogger(LoginController.class);
    @Autowired
    private UserService userService;

    /***
     * 微信登录返回结果处理
     *
     * @param model
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/wx_in")
    public String loginWX(Model model, HttpServletRequest request) throws IOException {
        log.info("开始跳转回来");
        String targetUrl = request.getParameter("target_url");
        log.info("TargetUrl=" + targetUrl);

        /**code是换取access_token的票据*/
        String code = request.getParameter("code");
        /**state是自定义参数*/
        String state = request.getParameter("state");

        log.info("微信返回："+code+"(------)"+state);


        Properties properties = PropertiesLoaderUtils.loadAllProperties("config.properties");
        String wxAPPID = properties.getProperty("wxAPPID");
        String wxAPPSECRET = properties.getProperty("wxAPPSECRET");


        /**根据code换取token*/
        String get_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + wxAPPID +
                "&secret=" + wxAPPSECRET +
                "&code=" + code +
                "&grant_type=authorization_code";

        String tokenJson = HttpClientUtils.getJson(get_token_url);

        /**json转换*/
        WxAccessTokenModel tokenModel = JSON.parseObject(tokenJson, WxAccessTokenModel.class);
        model.addAttribute("token", tokenModel);
        log.info("TOKEN:"+tokenJson);



        if (StringUtils.isEmpty(tokenModel.getOpenid()) == false) {
            /**根据openid和access_token获取用户信息*/
            String get_userInfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + tokenModel.getAccess_token() +
                    "&openid=" + tokenModel.getOpenid() +
                    "&lang=zh_CN";
            String userInfoJson = HttpClientUtils.getJson(get_userInfo_url);
            /**json转换*/
            WxUserInfoModel userInfoModel = JSON.parseObject(userInfoJson, WxUserInfoModel.class);
            model.addAttribute("user", userInfoModel);

            /**添加微信登录用户*/
            User user = userService.getUserByOpenId(tokenModel.getOpenid());
            if (user == null) {
                /**用户不存在-新增*/
                userService.insertWxUser(tokenModel, userInfoModel);
            } else {
                /**用户存在-更新*/
                userService.updateWxUser(user.getUserId(), tokenModel, userInfoModel);
            }

            /**设置登录*/
            SecurityUtils.getSubject().login(new UsernamePasswordToken(userInfoModel.getOpenid(), ""));
            if (StringUtils.isEmpty(targetUrl)) return "redirect:/home";
            else return "redirect:" + targetUrl;
        } else return "redirect:/login";

    }
}
